//
//  WHValidationHelper.m
//  LvZhongMagicKey
//
//  Created by 邓伟浩 on 2017/12/18.
//  Copyright © 2017年 邓伟浩. All rights reserved.
//

#import "WHValidationHelper.h"

@implementation WHValidationHelper

+ (BOOL)ValidTextField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *aStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
//    DLog(@"aStr=%@", aStr);
    if(string.length != 0 && [self isSudoku:aStr]) {
        return YES;
    }
    UITextRange *markedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:markedRange.start offset:0];
    if (position) {
        return YES;
    }
    
    BOOL isValidUserName = [WHValidationHelper validateStringLength:aStr length:10];
//    if (!isValidUserName) {
//        textField.text = [aStr substringToIndex:10];
//    }
    return isValidUserName;
}

/** 包含特殊字符 */
+ (BOOL)isSudoku:(NSString *)str {
    NSString *other = @"➋➌➍➎➏➐➑➒";
    NSString *lastStr = [str substringFromIndex:str.length-1];
    if (![other containsString:lastStr]) {
        return NO;
    }
    unsigned long len = lastStr.length;
    for (int i=0; i<len ;i++) {
        unichar a = [lastStr characterAtIndex:i];
        if(!((isalpha(a))
             ||(isalnum(a))
             ||((a=='_') || (a == '-'))
             ||((a >= 0x4e00 && a <= 0x9fa6))
             ||([other rangeOfString:lastStr].location != NSNotFound)
             ))
            return NO;
    }
    return YES;
}

+ (BOOL)validateIDCard:(NSString *)str {
    NSString *lengthRegex = NSStringFormat(@"^([0-9]{0,18})|([0-9]{0,17}((x)|(X)))$");
    NSPredicate *lengthPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lengthRegex];
    return [lengthPredicate evaluateWithObject:str];
}


+ (BOOL)validateStringLength:(NSString *)str length:(int)length {
    NSString *lengthRegex = NSStringFormat(@"^(.){0,%d}$", length);
    NSPredicate *lengthPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lengthRegex];
    return [lengthPredicate evaluateWithObject:str];
}

+ (BOOL)validatePasswordLength:(NSString *)str length:(int)length {
    NSString *lengthRegex = NSStringFormat(@"^[a-zA-Z0-9]{0,%d}$", length);
    NSPredicate *lengthPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lengthRegex];
    return [lengthPredicate evaluateWithObject:str];
}

+ (BOOL)validateNumber:(NSString *)numStr length:(int)length {
    NSString *lengthRegex = NSStringFormat(@"^[0-9]{0,%d}+$", length);
    NSPredicate *lengthPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lengthRegex];
    return [lengthPredicate evaluateWithObject:numStr];
}

+ (BOOL)validateDouble:(NSString *)str preLength:(int)preLength afterLength:(int)afterLength {
    NSString *lengthRegex = NSStringFormat(@"^[0-9]{0,%d}+(\\.([0-9]{0,%d}))?$", preLength, afterLength);
    NSPredicate *lengthPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lengthRegex];
    return [lengthPredicate evaluateWithObject:str];
}

/** 验证输入的金额, 最多2位小数 */
+ (BOOL)validateMoney:(NSString *)str {
    NSString *regex = @"^[0-9]+(\\.)?([0-9]{1,2})?$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:str];
}

/** 验证输入为0.5整数倍 */
+ (BOOL)validatePercentNum:(NSString *)str {
    NSString *regex = @"^[0-9]+(\\.)?[5]?$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:str];
}

+ (BOOL)isEmpty:(NSString *)str {
    if (!str) {
        return true;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

//数字
+ (BOOL) validateNumeric:(NSString *)numberic
{
    NSString *numbericRegex = @"^[0-9]*$";
    NSPredicate *numbericPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",numbericRegex];
    return [numbericPredicate evaluateWithObject:numberic];
}

//邮箱
+ (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//手机号码验证
+ (BOOL) validateMobile:(NSString *)mobile
{
//        NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"; // 以13, 15, 18开头,八个 \d 数字字符
    
    //    NSString *phoneRegex = @"^1\\d{10}$";  // 以1开头的11位数字
    NSString *phoneRegex = @"^\\d{11}$"; // 11为数字
//    NSString * phoneRegex = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
    
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

//车牌号验证
+ (BOOL) validateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    DLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}

//车型
+ (BOOL) validateCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}

//用户名
+ (BOOL) validateUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}

//密码
+ (BOOL)validatePassword:(NSString *)passWord {
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}

//昵称
+ (BOOL) validateNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}

//身份证号
+ (BOOL)validateIdentityCard:(NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

+ (BOOL)checkIdentityCardNo:(NSString*)cardNo {
    if (cardNo.length != 18) {
        return NO;
    }
    NSArray *codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    NSDictionary *checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil]  forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
    
    NSScanner *scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
    
    int val;
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    if (!isNum) {
        return NO;
    }
    
    int sumValue = 0;
    for (int i = 0; i < 17; i++) {
        sumValue += [[cardNo substringWithRange:NSMakeRange(i, 1)] intValue] * [[codeArray objectAtIndex:i] intValue];
    }
    
    NSString *strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d", sumValue % 11]];
    DLog(@"DEBUG strlast == %@", strlast);
    
    if ([strlast isEqualToString:[[cardNo substringWithRange:NSMakeRange(17, 1)] uppercaseString]]) {
        return YES;
    }
    return  NO;
}

+ (BOOL)checkBankCardNumber:(NSString *)cardNumber
{
    if (cardNumber.length == 0) {
        return NO;
    }
    int oddSum = 0;     // 奇数和
    int evenSum = 0;    // 偶数和
    int allSum = 0;     // 总和
    
    // 循环加和
    for (NSInteger i = 1; i <= cardNumber.length; i++)
    {
        NSString *theNumber = [cardNumber substringWithRange:NSMakeRange(cardNumber.length-i, 1)];
        int lastNumber = [theNumber intValue];
        if (i%2 == 0)
        {
            // 偶数位
            lastNumber *= 2;
            if (lastNumber > 9)
            {
                lastNumber -=9;
            }
            evenSum += lastNumber;
        }
        else
        {
            // 奇数位
            oddSum += lastNumber;
        }
    }
    allSum = oddSum + evenSum;
    // 是否合法
    if (allSum%10 == 0)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

@end
